<div class="m-bg">
<h1>SQL HAVING 子句</h1>
<h2>HAVING 子句</h2> <p>在 SQL 中增加 HAVING 子句原因是，WHERE 关键字无法与 Aggregate 函数一起使用。</p> <h3>SQL HAVING 语法</h3> <div class="code notranslate"><pre><code class="language-sql"><div> SELECT column_name, aggregate_function(column_name)<br/> FROM table_name<br/> WHERE column_name operator value<br/> GROUP BY column_name<br/> HAVING aggregate_function(column_name) operator value; </div></code></pre></div> <h2>演示数据库</h2> <p>在本教程中，我们将使用众所周知的 Northwind 样本数据库。</p> <p>下面是选自 "Orders" 表的数据：</p> <table class="reference notranslate">
<tr>
<th>OrderID</th> <th>CustomerID</th> <th>EmployeeID</th> <th>OrderDate</th> <th>ShipperID</th> </tr>
<tr>
<td>10248</td> <td>90</td> <td>5</td> <td>1996-07-04</td> <td>3</td> </tr>
<tr>
<td>10249</td> <td>81</td> <td>6</td> <td>1996-07-05</td> <td>1</td> </tr>
<tr>
<td>10250</td> <td>34</td> <td>4</td> <td>1996-07-08</td> <td>2</td> </tr>
</table>
<p>选自 "Employees" 表的数据：</p> <table class="reference notranslate">
<tr>
<th>EmployeeID</th> <th>LastName</th> <th>FirstName</th> <th>BirthDate</th> <th>Photo</th> <th>Notes</th> </tr>
<tr>
<td>1</td> <td>Davolio</td> <td>Nancy</td> <td>1968-12-08</td> <td>EmpID1.pic</td> <td>Education includes a BA....</td> </tr>
<tr>
<td>2</td> <td>Fuller</td> <td>Andrew</td> <td>1952-02-19</td> <td>EmpID2.pic</td> <td>Andrew received his BTS....</td> </tr>
<tr>
<td>3</td> <td>Leverling</td> <td>Janet</td> <td>1963-08-30</td> <td>EmpID3.pic</td> <td>Janet has a BS degree....</td> </tr>
</table>
<h2>SQL HAVING 实例</h2> <p>现在我们想要查找订单总数少于 2000 的客户。</p> <p>我们使用下面的 SQL 语句：</p> <p>下面的 SQL 语句查找注册超过 10 个订单的员工：</p> <div class="example margin-b-10"> <h2 class="example">实例</h2> <pre><code class="language-sql"><div class="example_code notranslate"> SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders<br/>INNER JOIN Employees<br/>ON Orders.EmployeeID=Employees.EmployeeID)<br/>GROUP BY LastName<br/>HAVING COUNT(Orders.OrderID) &gt; 10; </div></code></pre> </div> <p>现在我们想哟啊查找员工 "Davolio" 或 "Fuller" 是否拥有超过 25 个订单。</p> <p>我们在 SQL 语句中增加一个普通的 WHERE 子句：</p> <div class="example margin-b-10"> <h2 class="example">实例</h2> <pre><code class="language-sql"><div class="example_code notranslate"> SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders<br/>INNER JOIN Employees<br/>ON Orders.EmployeeID=Employees.EmployeeID<br/> WHERE LastName='Davolio' OR LastName='Fuller'<br/>GROUP BY LastName<br/>HAVING COUNT(Orders.OrderID) &gt; 25; </div></code></pre> </div> <div class="text-center padding-10 margin-t-5">
</div>
</div>